
import styles from './style.less';
import { connect, Link, history } from 'umi';
import DirMenu from '@/components/doc/DirMenu'
import { DOC_TYPE } from '@/consts/doc';
import { useEffect, useState, useRef } from 'react';
import { SearchOutlined, FileAddOutlined, MinusCircleOutlined, PlusOutlined ,QuestionCircleOutlined} from '@ant-design/icons'
import { Form, Input, Modal, Select, Table, Space, Button,Popover } from 'antd';
import { listStatusCode, saveStatusCode, updateStatusCode } from '@/services/doc/api'
import TextButton from '@/components/TextButton'
const { Option } = Select;

const enableTypeOptions = ["string", "number"]

const ApiStatusCode = (props) => {
    const {
        projectId,
        projectPermission,
        routeParam,
    } = props;

    const [currentDocData, setCurrentDocData] = useState();
    const [statusCodeList, setStatusCodeList] = useState([]);
    const [showedStatusCodeList, setShowedStatusCodeList] = useState([]);
    const [searchValue, setSearchValue] = useState({});
    const [currentDir, setCurrentDir] = useState();
    const [tableLoading, setTableLoading] = useState();
    const [permisson, setPermission] = useState();
    const [savingLoading,setSavingLoading] = useState(false)
    const [dirList, setDirList] = useState([{
        id: "0",
        title: "/"
    }])
    const [form] = Form.useForm()
    const menu = useRef();

    useEffect(() => {
        if (projectPermission) {
            setPermission(projectPermission?.api)
        }
    }, [projectPermission])

    useEffect(() => {
        if (currentDocData) {
            form.resetFields()
        }
    }, [currentDocData])

    useEffect(() => {
        if (currentDocData) {
            form.resetFields()
        }
    }, [currentDocData])

    useEffect(() => {
        if (projectId) {
            init();
        }
    }, [projectId])

    const init = () => {
        setSearchValue({})
        setCurrentDir()
        setTableLoading(true)
        listStatusCode(projectId, {}).then((result) => {
            setStatusCodeList(result.data)
            setTableLoading(false)
        })
    }

    useEffect(() => {
        if (searchValue) {
            setShowedStatusCodeList(statusCodeList.filter(item => {
                let dirCond = searchValue.dirId ? item.dirId === searchValue.dirId : true;
                let searchTextCond = searchValue.search ? (item.name?.indexOf(searchValue.search) > -1 || item.description?.indexOf(searchValue.search) > -1) : true
                let content = item.content?.map(item => item.name + ":" + item.description).join(";") || "";
                let contentSearch = searchValue.search ? (content?.indexOf(searchValue.search) > -1)     : true
                return dirCond && (searchTextCond || contentSearch);
            }))
        } else {
            setShowedStatusCodeList([...statusCodeList])
        }
    }, [searchValue, statusCodeList])

    const onDirTreeData = (dirTreeData) => {
        if (dirTreeData) {
            let dirList = [{
                id: "0",
                title: "/"
            }]
            dirTreeData.forEach(dir => {
                if (dir.isDir) {
                    dirList.push({
                        id: dir.id,
                        title: dir.title
                    })
                }
            })
            setDirList(dirList)
        }
    }

    const deleteDocDir = (docDir, callBack) => {
        // 删除接口文档目录
    }


    const addErrorCode = (dir, dirRoutes) => {
        setCurrentDocData({
            dirId: dir.id,
            type: "string"
        })
    }

    const onUpdateErrorCode = (errorCode) => {
        setCurrentDocData({
            ...errorCode,
            type: errorCode.type
        })
    }

    const onSaveErrorCode = async (doc) => {
        let values = await form.validateFields()
        setSavingLoading(true)
        if (currentDocData.id) {
            updateStatusCode(projectId, currentDocData.id, values).then(result => {
                setCurrentDocData(null)
                let newStatusCodeList = statusCodeList.map((item) => {
                    if (item.id === currentDocData.id) {
                        return {
                            ...item,
                            ...values
                        }
                    }
                    return item
                })
                setStatusCodeList(newStatusCodeList)
                setSavingLoading(false)
            })
        } else {
            saveStatusCode(projectId, values).then(result => {
                setCurrentDocData(null)
                statusCodeList.push({
                    id: result.data,
                    ...values
                })
                setStatusCodeList([...statusCodeList])
                setSavingLoading(false)
            })
        }
    }

    const onClickDir = (docNode, dirRoutes) => {
        setCurrentDir(docNode)
        setSearchValue({
            ...searchValue,
            dirId: docNode.id,
        })
    }

    const columns = [{
        title: "名称",
        dataIndex: 'name',
        width: "15%",
        sorter: (a, b) => a.name && a.name.localeCompare(b.name),
    }, {
        title: "类型",
        dataIndex: 'type',
        width: "10%",
        }, {
        title: "描述",
        width: "25%",
        dataIndex: 'description',
        sorter: (a, b) => a.description && a.description.localeCompare(b.description),
    }, {
        title: "状态",
        width: "25%",
        dataIndex: 'content',
        render:(text,record) => {
            let contentDesc = ""
            if (record.content) {
               return record.content.map(item => item.name + ":" + item.description).join(";")
            } 
            return ""
        }
    }]

    const renderTableColumn = () => {
        if (permisson?.errcode) {
            columns.push({
                title: "操作",
                dataIndex: 'action',
                render: (text, record) => <Space>
                    <TextButton onClick={() => onUpdateErrorCode(record)}>修改</TextButton>
                    <TextButton type="danger">删除</TextButton>
                </Space>
            })
        }
        return columns;
    }

    return <div className={styles.statusCodeBody}>
        <DirMenu
            ref={menu}
            title={<TextButton onClick={init}>所有状态码</TextButton>}
            projectId={projectId}
            enableLevel={1}
            width="200px"
            docType={DOC_TYPE.API_STATUS}
            deleteDir={deleteDocDir}
            onClickDir={onClickDir}
            onDirTreeData={onDirTreeData}
            switcherIcon={null}
            dirMoreActions={["rename","delete"]}
            rootMore={<div></div>}
            dirOpertion={[
                {
                    key: "addErrorCode",
                    icon: <FileAddOutlined />,
                    name: "新建状态码",
                    onClick: addErrorCode
                }
            ]}
        >
        </DirMenu>
        <div className={styles.statusCode} style={{
            width: "calc(100% - 200px)"
        }}>
            <div className={styles.statusCodeInfo}>
                <Space className={styles.opertion}>
                    <div className={styles.route}>
                        {currentDir ? currentDir.title : "全部"}
                    </div>
                    <Button type="primary" onClick={() => {
                        addErrorCode(currentDir || {
                            id: "0",
                            type: "1"
                        })
                    }}>新增</Button>
                    <Popover content={<p>
                        状态码:<br />
                        1. 建议状态码的名称为字母或下划线，与属性字段名保持一致。<br />
                    </p>}><QuestionCircleOutlined /></Popover>
                </Space>
                <div className={styles.searchInput}>
                    <Input bordered={false}
                        allowClear
                        value={searchValue?.search}
                        onChange={(e) => {
                            setSearchValue({
                                ...searchValue,
                                search: e.target.value
                            })
                        }}
                        prefix={<SearchOutlined />} placeholder={"名称/描述/内容"}></Input>
                </div>

            </div>
            <div className={styles.statusCodeList}>
                <Table
                    size="small"
                    rowKey="id"
                    loading={tableLoading}
                    scroll={{ y: 480 }}
                    bordered={false}
                    pagination={false}
                    columns={renderTableColumn()}
                    dataSource={showedStatusCodeList}>

                </Table>
            </div>

        </div>

        <Modal
            title={currentDocData?.id ? "修改状态码" : "新增状态码"}
            visible={!!currentDocData}
            closable
            zIndex={1051}
            onCancel={() => {
                setCurrentDocData(null)
            }}
            confirmLoading={savingLoading}
            onOk={onSaveErrorCode}
        >
            <Form form={form} className={styles.form} initialValues={currentDocData}>
                <Form.Item name="dirId" label="目录">
                    <Select placeholder="请选择目录" dropdownStyle={{ zIndex: 1060 }}>
                        {dirList.map(dir => <Option key={dir.id} value={dir.id}>{dir.title}</Option>)}
                    </Select>
                </Form.Item>
                <Form.Item name="name" label="名字" rules={[{
                    required: true,
                    message: "名称长度为1～40",
                    min: 1,
                    max: 40
                }]}>
                    <Input disabled={!!currentDocData?.id} placeholder="请输入名字"></Input>
                </Form.Item>
                <Form.Item name="type" label="类型" >
                    <Select placeholder="请选择类型" dropdownStyle={{ zIndex: 1060 }}>
                        {enableTypeOptions.map(type => <Option key={type} value={type}>{type}</Option>)}
                    </Select>
                </Form.Item>
                <Form.Item name="description" label="描述" rules={[{
                    required: true,
                    message: "描述长度为1～40",
                    min: 1,
                    max: 40
                }]}>
                    <Input placeholder="请选择描述"></Input>
                </Form.Item>
                <Form.Item label="内容">
                    <Form.List name="content" >
                        {(fields, { add, remove }) => (
                            <>
                                {fields.map(({ key, name, fieldKey, ...restField }) => (
                                    <Space key={key} style={{ padding: "4px" }} align="center">
                                        <Form.Item
                                            {...restField}
                                            name={[name, 'name']}
                                            style={{ marginBottom: 0 }}
                                            fieldKey={[fieldKey, 'name']}
                                            rules={[{ required: true, message: '请输入名称' }]}
                                        >
                                            <Input placeholder="名称" maxLength={15} style={{ width: "100%" }} />
                                        </Form.Item>
                                        <Form.Item
                                            {...restField}
                                            name={[name, 'description']}
                                            style={{ marginBottom: 0 }}
                                            fieldKey={[fieldKey, 'value']}
                                            rules={[{ required: true, message: '请输入内容' }]}
                                        >
                                            <Input placeholder="内容" maxLength={40} style={{ width: "100%" }} />
                                        </Form.Item>
                                        <MinusCircleOutlined onClick={() => remove(name)} />
                                    </Space>
                                ))}
                                <Form.Item style={{ padding: "4px" }}>
                                    <Button type="dashed" onClick={() => {
                                        if (fields && fields.length > 20) {
                                            message.error("最多只能添加20组")
                                            return
                                        }
                                        add()
                                    }} block style={{ width: "240px" }} icon={<PlusOutlined />}>新增 </Button>
                                </Form.Item>
                            </>
                        )}
                    </Form.List>
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default ApiStatusCode;